package com.xyhuo.leetcode.december;

import com.xyhuo.leetcode.common.ListNode;

/**
 * 旋转链表
 * https://leetcode.cn/problems/rotate-list/
 *
 * @time 2023/12/25
 */
public class RotateRight {

    public ListNode rotateRight(ListNode head, int k) {
        if (head == null) {
            return null;
        }
        int len = 0;
        ListNode lenTmp = head;
        ListNode lastNode = null;
        while (true) {
            len++;
            if (lenTmp.next == null) {
                lastNode = lenTmp;
                break;
            }
            lenTmp = lenTmp.next;
        }
        k = k % len;
        if (k == 0) {
            return head;
        }

        ListNode tmpLast = null;
        ListNode tmp = head;
        int step = len - k;
        while (step > 0) {
            step--;
            tmpLast = tmp;
            tmp = tmp.next;
            if (step == 0) {
                tmpLast.next = null;
            }
        }
        lastNode.next = head;

        return tmp;
    }

}
